import fs from "fs";
import path from "path";

// 读取 meta 文件的函数
function readMetaFile(metaFilePath) {
  if (!fs.existsSync(metaFilePath)) {
    return {};
  }
  
  try {
    const content = fs.readFileSync(metaFilePath, 'utf-8');
    // 移除可能的 export default 或 module.exports
    const cleanContent = content
      .replace(/^export\s+default\s*/, '')
      .replace(/^module\.exports\s*=\s*/, '')
      .trim();
    
    // 使用 Function 构造器来安全地执行代码并返回对象
    const meta = new Function('return ' + cleanContent)();
    return meta || {};
  } catch (error) {
    console.warn(`Failed to read meta file: ${metaFilePath}`, error.message);
    return {};
  }
}

// 生成路由数组的方法
function generateRoutes(dir, basePath, options) {
  const files = fs.readdirSync(dir);
  return files.flatMap((file) => {
    const fullPath = path.resolve(dir, file);
    const relativePath = path.relative(basePath, fullPath);
    if (fs.statSync(fullPath).isDirectory()) {
      return generateRoutes(fullPath, basePath, options);
    }
    if (file.endsWith(".vue")) {
      const routePath = relativePath
        .replace(/\\/g, "/")
        .replace(/\.vue$/, "")
        .replace(/\/index$/, "")
        .replace(/\/_/g, "/:");

      const parts = routePath.split("/").filter(Boolean);
      if (
        parts.length > 1 &&
        parts[parts.length - 1] === parts[parts.length - 2]
      ) {
        parts.pop();
      }
      const finalPath = "/" + parts.join("/").toLowerCase();
      const pagesDir = options.pagesDir;
      const comrelativePath = "/" + pagesDir + "/" + relativePath;
      const metaFilePath = fullPath.replace(".vue", ".meta.js");
      const meta = readMetaFile(metaFilePath);
      return [
        {
          path: finalPath,
          ...meta,
          component: `() => import('${comrelativePath}')`,
        },
      ];
    }
    return [];
  });
}

export default function VitePluginAutoRoutes(options = {}) {
  const { pagesDir = "src/views", routesFile = "src/router/autoRoutes.js" } =
    options;
  return {
    name: "vite-plugin-auto-routes-byfangq",
    configResolved(config) {
      //vite.config 的绝对路径config.root
      // pagesPath是pagesDir的绝对路径
      const pagesPath = path.resolve(config.root, pagesDir);
      // 生成路由数组
      const routes = generateRoutes(pagesPath, pagesPath, options);
      const routesFileContent = `export const routes = ${JSON.stringify(routes, null, 2).replace(
          /"component": "(.*)"/g,
          "component: $1"
        )}
      `;
      fs.writeFileSync(
        path.resolve(config.root, routesFile),
        routesFileContent
      );
    },
  };
}
